<template>
    <div class="phoneKey">
        <!-- 顶部状态栏 -->

        <!-- 基本信息 -->
        <img class="bigImg" :src="loginImg" alt="">
        <van-cell-group id="shuru">
            <van-field placeholder="请输入手机号" label="手机号" :left-icon="phoneImg" v-model="phone" @blur="panduan1()"
                :error-message="errorMessage" />
            <van-field v-model="code" center clearable :left-icon="codeImg" label="验证码" type="number"
                placeholder="请输入验证码">
                <van-button slot="button" size="small" v-if="showAgain" type="info" color="#4b77e4" @click="getCode">
                    发送验证码</van-button>
                <van-button slot="button" size="small" v-else type="info" color="#4b77e4" disabled>
                    {{sec}}秒重新发送</van-button>
            </van-field>
            <p @click="login">立即使用</p>
        </van-cell-group>
        <div id="text" @click="lookAgreement">登录使用代表您已同意<span>《服务协议》</span></div>
    </div>
</template>
<script>
    // 监听返回
    // document.addEventListener('plusready', function () {
    //     var webview = plus.webview.currentWebview();
    //     plus.key.addEventListener('backbutton', function () {
    //         webview.canBack(function (e) {
    //             if (e.canBack) {
    //                 webview.back();
    //             } else {
    //                 webview.close(); //hide,quit
    //                 //plus.runtime.quit();
    //             }
    //         })
    //     });
    // });
    document.addEventListener("plusready", function() { 
        // 注册返回按键事件 
        plus.key.addEventListener('backbutton', function() { 
            // 事件处理 
            window.history.back();
        }, false); 
    });
    import { Toast } from "vant"
    import { Icon, NumberKeyboard } from 'vant'
    import { mapState, mapMutations } from 'vuex'
    export default {
        // 当前组件的名称

        data() {
            return {
                phone: "",
                errorMessage: "",
                aaa: false,
                code: "",
                phoneImg: require("../assets/img/phone.png"),
                codeImg: require("../assets/img/code.png"),
                loginImg: require("../assets/img/login.png"),
                type: "发送验证码",
                sec: 60,
                showAgain: true,
                sessionid: ""
            }
        },

        // 在当前组件中添加其他的自定义组件
        components: {

        },

        /*
            在computed中添加mapState
            如果computed中只有一个辅助函数，后面可以直接写成函数名
        */
        computed: mapState(['token', 'userInfo', 'userid']), // this.token相当于this.$store.state.token

        methods: {
            ...mapMutations(['changeToken', 'changeUserid', 'changeuserPhone']),
            // 使用协议
            lookAgreement() {
                this.$router.push("Agreement")
            },
            panduan1() {

                // var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                // this.errorMessage = myreg.test(this.phone) ? "" : "请输入正确的手机号"
            },
            getCode() {
                let that = this
                const { phone } = this
                // 前端检验，用户名和密码必填
                if (!phone) {
                    Toast({
                        message: '请填写手机号码', // 显示内容

                        duration: 1000 // 显示时间
                    })

                    return false
                }
                //正则验证手机号码
                var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                if (!myreg.test(phone)) {
                    Toast({
                        message: '请输入正确的手机号码', // 显示内容
                        duration: 1000 // 显示时间
                    })
                    return false;
                }
                this.time()



                this.$axios.get("/new/login/verifycode", {
                    params: {
                        phone: phone,
                    }
                }).then((res) => {
                    console.log(res);
                    const { data, status } = res

                    if (status == 200 && data.code == 200) {
                        Toast(data.message)
                        that.sessionid = data.sessionid
                        console.log(data.sessionid)
                        console.log(data.vcode)

                    } else {
                        Toast(data.message)
                    }

                })
            },
            time() {
                this.showAgain = false
                this.sec = 60
                var timer = setInterval(() => {
                    this.sec = this.sec - 1;
                    if (this.sec == 0) {
                        this.showAgain = true
                        clearInterval(timer)
                    } else {

                    }
                }, 1000)

            },
            login() {
                let that = this
                const { phone, code, sessionid } = this
                // 前端检验，用户名和密码必填
                if (!phone || !code) {
                    Toast({
                        message: '请填写手机号和验证码', // 显示内容

                        duration: 1000 // 显示时间
                    })

                    return false
                }
                //正则验证手机号码
                var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                if (!myreg.test(phone)) {
                    Toast({
                        message: '请输入正确的手机号码', // 显示内容
                        duration: 1000 // 显示时间
                    })
                    return false;
                }
                this.$axios.get("/new/verdict/verifCode", {
                    params: {
                        phone,
                        vcode: code,
                        sessionid
                    }
                }).then((res) => {
                    console.log(res);
                    const { data, status } = res

                    if (status == 200 && data.code == 200) {
                        const { token, userid } = data
                        // 把token存到本地
                        localStorage.setItem('token', token)
                        localStorage.setItem('userid', userid)
                        localStorage.setItem('userPhone', phone)
                        console.log(userid)
                        // 把token存到store
                        this.changeToken(token)
                        this.changeUserid(userid)
                        this.changeuserPhone(phone)
                        this.$router.push(
                            {
                                name: 'home1',
                                params: {
                                    username: phone
                                }
                            }
                        )
                        Toast(data.message)
                    } else {
                        Toast(data.message)
                    }

                })
            }
        },
        created() {
            const token = localStorage.getItem('token')
            if (token) {
                this.$router.push("home1")
            }
        },
        mounted() {
            var windheight = window.innerHeight;//页面加载时的高度
            // var immersed = 0;
            // var bigImg = document.querySelector('.bigImg');
            // console.log(666, t)
            // var ms = (/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);
            // if (ms && ms.length >= 3) { // 当前环境为沉浸式状态栏模式  
            //     immersed = parseFloat(ms[2]);// 获取状态栏的高度  

            //     console.log(immersed)

            //     bigImg.style.marginTop = (-immersed) + 'px';
            // }

            var bottomx = document.getElementById('text'); //底部导航
            window.onresize = () => {
                var docheight = window.innerHeight;//改变后端高度
                if (docheight < windheight) {
                    bottomx.style.position = 'static';
                    bottomx.style.transform = "none";
                } else {
                    bottomx.style.position = 'fixed';
                    bottomx.style.transform = "translate(-50%, 0)"
                }
            }

        },
        // 生命周期函数,当数据发生改变并且导致视图发生相应的改变
        updated() {
            // console.log('updated')
        },
        // 生命周期函数,组件被销毁
        destroyed() {
            console.log("组件销毁", 666)
            console.log('destroyed')
            window.onresize = null;
        },

        // 生命周期函数,离开缓存组件
        deactivated() {
            console.log('deactivated')
        },
        // 离开路由之前,它会在deactivated之前调用

    }
</script>

<!-- 添加scoped属性,将样式的作用域限制在当前组件内,不会影响子组件 -->
<style lang="scss" scoped>
    .phoneKey {
        height: 100vh;
        /* position: fixed; */
    }

    #shuru {
        /* position: fixed;
        bottom: 150px; */

        p {

            width: 40%;
            background-color: #4b77e4;
            color: white;
            text-align: center;
            margin: 20px auto;
            height: 30px;
            line-height: 30px;
            border-radius: 4px;
        }
    }

    .bigImg {
        width: 100%;
        height: auto;

    }

    #text {
        text-align: center;
        position: fixed;
        bottom: 8px;
        left: 50%;
        transform: translate(-50%, 0);
        white-space: nowrap;

        span {
            color: #4b77e4;
        }
    }
</style>